import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';

@Catch(HttpException)
export class CustomExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    const res = exception.getResponse() as any;

    if (res.message) {
      res.message = Array.isArray(res.message) ? res.message : [res.message];
    }

    response
      .json({
        code: exception.getStatus(),
        message: 'fail',
        data: res?.message?.join(',') || exception.message,
      })
      .end();
  }
}
